package cn.com.dashihui.web.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import com.jfinal.kit.StrKit;
import com.jfinal.upload.UploadFile;

import cn.com.dashihui.kit.DirKit;
import cn.com.dashihui.web.base.BaseController;
import cn.com.dashihui.web.dao.Ad;
import cn.com.dashihui.web.service.AdService;

@RequiresAuthentication
public class AdController extends BaseController{
	private AdService service = new AdService();
    
	@RequiresPermissions("bus:ad:index")
    public void index(){
    	setAttr("adList", service.findAll());
        render("index.jsp");
    }
    
	@RequiresPermissions("bus:ad:sort")
    public void doSort(){
    	Map<String,String[]> params = getParaMap();
    	if(params!=null&&params.size()!=0&&params.containsKey("sortKey")){
    		String sortKey = params.get("sortKey")[0];
    		Map<String,String> sortMap = new HashMap<String,String>();
    		for(String key : params.keySet()){
    			if(!key.equals("sortKey")){
    				String id = key.replace(sortKey, "");
    				String no = params.get(key)[0];
    				if(StrKit.isBlank(no)||no.length()>3){
    					no = "0";
    				}
    				sortMap.put(id, no);
    			}
    		}
    		service.sortAd(sortMap);
    		renderSuccess();
    		return;
    	}
    	renderFailed();
    }
    
	@RequiresPermissions("bus:ad:add")
	public void toAdd(){
		render("add.jsp");
	}
	
	/**
	 * 添加
	 * @return -1：异常，0：成功，1：图片为空，2：图片上传失败
	 */
	@RequiresPermissions("bus:ad:add")
	public void doAdd(){
		UploadFile thumb = getFile("thumb");
		//轮播类型
		int validtime0 = getParaToInt("validtime0");
		//商品ID
		String goodsid= getPara("goodsid");
		//链接URL
		String link = getPara("link");
		//背景色
		String background=getPara("background");
		//保存
		Ad ad = new Ad().set("background", background);
		if (validtime0 == 1 && !StrKit.isBlank(goodsid)) {
			ad.set("link","http://api.nczywc.cn/h5/#/pages/product/product?id="+goodsid);
		}
		if (validtime0 == 2 && !StrKit.isBlank(link)) {
			ad.set("link", link);
		}
		//如果上传了图片，则上传至FTP，并记录图片文件名
		if(thumb!=null){
			String thumbFileName;
			String dir = DirKit.getDir(DirKit.AD);
			try {
				thumbFileName = uploadToFtp(dir,thumb);
			} catch (IOException e) {
				e.printStackTrace();
				renderResult(2);
				return;
			}
			ad.set("thumb", dir.concat(thumbFileName));
			if(service.addAd(ad)){
				renderSuccess(service.findById(ad.getInt("id")));
				return;
			}
		}else{
			renderResult(1);
			return;
		}
	}
	
	@RequiresPermissions("bus:ad:edit")
	public void toEdit(){
		int id = getParaToInt(0,0);
		if(id!=0){
			setAttr("object", service.findById(id));
		}
		render("edit.jsp");
	}
	
	/**
	 * 更新
	 * @return -1：异常，0：成功，1：图片上传失败
	 */
	@RequiresPermissions("bus:ad:edit")
	public void doEdit(){
		UploadFile thumb = getFile("thumb");
		//ID
		String adid = getPara("adid");
		//链接URL
		String link = getPara("link");
		//背景色
		String background=getPara("background");
		//更新
		Ad ad = new Ad().set("id",adid).set("link", link).set("background", background);
		//旧图片
		String thumbOld = getPara("thumbOld");
		if(thumb!=null){
			//如果修改了图片，则上传新图片，删除旧图片
			String thumbFileName;
			String dir = DirKit.getDir(DirKit.AD);
			try {
				thumbFileName = uploadToFtp(dir,thumb);
			} catch (IOException e) {
				e.printStackTrace();
				renderResult(1);
				return;
			}
			ad.set("thumb", dir.concat(thumbFileName));
			if(service.editAd(ad)){
				try {
					deleteFromFtp(thumbOld);
				} catch (IOException e) {
					logger.error("更新时，旧图片"+thumbOld+"删除失败！");
					e.printStackTrace();
				}
				renderSuccess(service.findById(Integer.valueOf(adid)));
				return;
			}
		}else if(service.editAd(ad)){
			renderSuccess(service.findById(Integer.valueOf(adid)));
			return;
		}
	}
	
	/**
	 * 删除
	 * @return -1：删除失败，0：删除成功
	 */
	@RequiresPermissions("bus:ad:delete")
	public void doDelete(){
		int id = getParaToInt(0,0);
		if(id!=0){
			Ad ad = service.findById(id);
			//先判断社区如果上传了图片，则删除图片
			if(!StrKit.isBlank(ad.getStr("thumb"))){
				try {
					deleteFromFtp(ad.getStr("thumb"));
				} catch (IOException e) {
					logger.error("删除时，相关图片"+ad.getStr("thumb")+"删除失败！");
					e.printStackTrace();
				}
			}
			//然后再对记录进行删除
			ad.delete();
//			logger.info("删除广告位【"+id+"】，及其图片");
			renderSuccess();
			return;
		}
		renderFailed();
	}
}
